from django.shortcuts import render

# Create your views here.

"""
获取所有书籍      GET         books/
获取一本书籍      GET         books/pk/

获取省份信息      GET         areas/infos/
获取市,区县信息    GET         areas/infos/pk/

获取省份信息的 sql语句
select * from tb_areas where parent_id is Null;

获取市的信息
select * from tb_areas where parent_id=110000;
获取区县信息
select * from tb_areas where parent_id=110100;

获取省份信息      GET         areas/infos/

#1.获取所有省份信息
areas = Area.objects.filter(parent_id__isnull=True)
#2.创建序列化器,让序列化器将对象转换为字典
serailzier = AreaSerializer(areas,many=True)
#3.返回响应
return Response(serializer.data)


获取市,区县信息    GET         areas/infos/pk/

继承自APIView 如果实现

1.获取数据
areas = Area.objects.filter(parent_id=pk)
2.创建序列化器,让序列化器将对象转换为字典
serializer = AreaSerializer(areas,many=True)
3.返回响应
return Response(serializer.data)
"""

from rest_framework.viewsets import ModelViewSet,ReadOnlyModelViewSet
from .models import Area
from .serializers import AreaSerializer,AreaSubSerializer
"""
获取省份信息      GET         areas/infos/
获取市,区县信息    GET         areas/infos/pk/
"""
from rest_framework_extensions.cache.mixins import ListCacheResponseMixin,RetrieveCacheResponseMixin
from rest_framework_extensions.mixins import CacheResponseMixin
class AreaViewSet(CacheResponseMixin,ReadOnlyModelViewSet):

	pagination_class = None

	# ReadOnlyModelViewSet 是继承自 GenericAPIView
	# GenericAPIView 对列表视图和详情视图做了通用支持
	# 一般要设置queryset 和 serializer_class

	# queryset = Area.objects.all()   # 区县信息
	# queryset = Area.objects.filter(parent_id__isnull=True)   # 省的信息

	def get_queryset(self):
		if self.action == 'list':
			# 就是在获取省份信息
			return Area.objects.filter(parent_id__isnull=True)
		else:
			# 获取市，区县信息
			return Area.objects.all()

	# serializer_class = AreaSerializer   省
	# serializer_class = AreaSubSerializer  市

	def get_serializer_class(self):
		if self.action == 'list':
			return AreaSerializer
		else:
			return AreaSubSerializer


